| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- import { NextRequest, NextResponse } from 'next/server';
- import { getServerSession } from 'next-auth';
- import { authOptions } from '@/lib/auth';
- import { db } from '@/lib/db';
- import { sections, classes, periods, studentEnrollments, eq, and, ne } from '@/lib/db/schema';
- interface RouteContext {
- params: Promise<{ id: string }>;
- }
- export async function PUT(request: NextRequest, context: RouteContext) {
- try {
- const session = await getServerSession(authOptions);
-
- if (!session?.user || session.user.role !== 'admin') {
- return NextResponse.json(
- { error: 'No autorizado' },
- { status: 401 }
- );
- }
- const { id } = await context.params;
- const { name, classId, periodId, maxStudents } = await request.json();
- // Validaciones
- if (!name || !classId || !periodId || !maxStudents) {
- return NextResponse.json(
- { error: 'Todos los campos son requeridos' },
- { status: 400 }
- );
- }
- if (typeof maxStudents !== 'number' || maxStudents < 1) {
- return NextResponse.json(
- { error: 'El número máximo de estudiantes debe ser mayor a 0' },
- { status: 400 }
- );
- }
- // Verificar si la sección existe
- const existingSection = await db
- .select()
- .from(sections)
- .where(eq(sections.id, id))
- .limit(1);
- if (existingSection.length === 0) {
- return NextResponse.json(
- { error: 'Sección no encontrada' },
- { status: 404 }
- );
- }
- // Verificar si la clase existe
- const existingClass = await db
- .select()
- .from(classes)
- .where(eq(classes.id, classId))
- .limit(1);
- if (existingClass.length === 0) {
- return NextResponse.json(
- { error: 'La clase seleccionada no existe' },
- { status: 400 }
- );
- }
- // Verificar si el período existe
- const existingPeriod = await db
- .select()
- .from(periods)
- .where(eq(periods.id, periodId))
- .limit(1);
- if (existingPeriod.length === 0) {
- return NextResponse.json(
- { error: 'El período seleccionado no existe' },
- { status: 400 }
- );
- }
- // Verificar si ya existe otra sección con el mismo nombre para la misma clase y período
- const duplicateSection = await db
- .select()
- .from(sections)
- .where(and(
- eq(sections.name, name),
- eq(sections.classId, classId),
- eq(sections.periodId, periodId),
- ne(sections.id, id)
- ))
- .limit(1);
- if (duplicateSection.length > 0) {
- return NextResponse.json(
- { error: 'Ya existe otra sección con este nombre para la misma clase y período' },
- { status: 400 }
- );
- }
- // Verificar si el nuevo límite de estudiantes es menor al número actual de estudiantes inscritos
- const currentEnrollments = await db
- .select()
- .from(studentEnrollments)
- .where(eq(studentEnrollments.sectionId, id));
- if (maxStudents < currentEnrollments.length) {
- return NextResponse.json(
- { error: `No se puede reducir el límite a ${maxStudents} porque hay ${currentEnrollments.length} estudiantes inscritos` },
- { status: 400 }
- );
- }
- // Actualizar sección
- const updatedSection = await db
- .update(sections)
- .set({
- name,
- classId,
- periodId,
- maxStudents,
- updatedAt: new Date(),
- })
- .where(eq(sections.id, id))
- .returning({
- id: sections.id,
- name: sections.name,
- classId: sections.classId,
- periodId: sections.periodId,
- maxStudents: sections.maxStudents,
- isActive: sections.isActive,
- updatedAt: sections.updatedAt,
- });
- return NextResponse.json(updatedSection[0]);
- } catch (error) {
- console.error('Error updating section:', error);
- return NextResponse.json(
- { error: 'Error interno del servidor' },
- { status: 500 }
- );
- }
- }
- export async function DELETE(request: NextRequest, context: RouteContext) {
- try {
- const session = await getServerSession(authOptions);
-
- if (!session?.user || session.user.role !== 'admin') {
- return NextResponse.json(
- { error: 'No autorizado' },
- { status: 401 }
- );
- }
- const { id } = await context.params;
- // Verificar si la sección existe
- const existingSection = await db
- .select()
- .from(sections)
- .where(eq(sections.id, id))
- .limit(1);
- if (existingSection.length === 0) {
- return NextResponse.json(
- { error: 'Sección no encontrada' },
- { status: 404 }
- );
- }
- // Verificar si la sección tiene estudiantes inscritos
- const enrolledStudents = await db
- .select()
- .from(studentEnrollments)
- .where(eq(studentEnrollments.sectionId, id))
- .limit(1);
- if (enrolledStudents.length > 0) {
- return NextResponse.json(
- { error: 'No se puede eliminar la sección porque tiene estudiantes inscritos' },
- { status: 400 }
- );
- }
- // Eliminar sección (soft delete)
- await db
- .update(sections)
- .set({
- isActive: false,
- updatedAt: new Date(),
- })
- .where(eq(sections.id, id));
- return NextResponse.json(
- { message: 'Sección eliminada exitosamente' },
- { status: 200 }
- );
- } catch (error) {
- console.error('Error deleting section:', error);
- return NextResponse.json(
- { error: 'Error interno del servidor' },
- { status: 500 }
- );
- }
- }
|